import Vue from 'vue'
import { login } from '@/api/login'
import { getMemberInfo } from '@/api/public'
import { ACCESS_TOKEN,ROLE_NAME,USERINFO } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          Vue.ls.set(ACCESS_TOKEN, response.data, 7 * 24 * 60 * 60 * 1000)    
          commit('SET_TOKEN', response.data)    
          resolve()
        }).catch(error => {
          reject(error)
        })
         
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getMemberInfo().then((response)=>{ 
          Vue.ls.set(ROLE_NAME,response.data.roleName) 
          Vue.ls.set(USERINFO,response.data)         
          commit('SET_NAME', { name: "result.name", welcome: welcome() })
          commit('SET_ROLES', 'result.role')
          commit('SET_ROLES', 'admin')
          commit('SET_AVATAR', '')
          resolve(response)                
        }) 

       
         
               
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {

          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
          resolve()

        // logout(state.token).then(() => {
        //   resolve()
        // }).catch(() => {
        //   resolve()
        // }).finally(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   Vue.ls.remove(ACCESS_TOKEN)
        // })
      })
    }

  }
}

export default user
